#include "mapitem.h"

MapItem::MapItem()
{

}

MapItem::MapItem(FixedUnit *unit)
{
    this->addUnit(unit);
}


MapItem::~MapItem()
{
}


FixedUnit *MapItem::getUnitAt(int pos) {return m_units.at(pos);}
int MapItem::getNbUnits() {return m_units.count();}
int MapItem::getRow() {return this->row;}
int MapItem::getColumn() {return this->column;}

void MapItem::setRow(int i) {this->row = i;}
void MapItem::setColumn(int j) {this->column = j;}


void MapItem::addUnit(FixedUnit *unit)
{
    m_units.append(unit);

}

void MapItem::removeUnitAt(int pos)
{
    delete m_units.at(pos);
    m_units.removeAt(pos);
}


int MapItem::findUnit(Unit::Type type)
{
    for(int i = 0; i < m_units.count(); i++)
        if(type == m_units.at(i)->getType()) return i;

    return -1;
}

bool MapItem::isEmpty() {return m_units.isEmpty();}


void MapItem::draw(QPainter *painter)
{
    foreach(FixedUnit *unit, m_units)
        unit->draw(painter);
}

void MapItem::serializeDebug(QDebug &dbg)
{
    dbg << "MapItem( nbunit:" << getNbUnits();
    foreach(FixedUnit *unit, m_units)
    {
        dbg << "type:" << unit->getType();
        dbg << unit;
    }

    dbg << ")";
}


void MapItem::serializeIn(QDataStream &in)
{
    int n, type;
    FixedUnit *unit;

    in >> n;
    for(int i = 0; i < n; i++)
    {
        in >> type;
        switch (type)
        {
            case Unit::Fruit : unit = new Fruit(); break;
            case Unit::Block : unit = new Block(); break;
            case Unit::Door : unit = new Door(); break;
        }
        in >> unit;
        addUnit(unit);

        //in >> (unit = makeFixedUnit(type));
        //addUnit(unit);
    }
}

void MapItem::serializeOut(QDataStream &out)
{
    out << getNbUnits();
    foreach(FixedUnit *unit, m_units)
    {
        out << (qint32)unit->getType();
        out << unit;
    }
}


FixedUnit* MapItem::makeFixedUnit(int type)
{
    switch(type)
    {
        case Unit::Block : return new Block();
        case Unit::Fruit : return new Fruit();
        case Unit::Door : return new Door();
        default : return NULL;
    }
}



QDataStream & operator << (QDataStream &out, MapItem* item)
{
    item->serializeOut(out);
    return out;
}

QDataStream & operator >> (QDataStream &in,  MapItem* item)
{
    item->serializeIn(in);
    return in;
}

QDebug operator<<(QDebug dbg, MapItem* item)
{
    item->serializeDebug(dbg);
    return dbg;
}
